<?php
namespace app\api\controller\newfile;

use think\Controller;
use think\Request;
use app\common\model\newmodel\Factory as FactoryModel;
use app\common\model\newmodel\User as UserModel;
use app\common\model\power\Rolepower;
use app\common\model\newmodel\UserFactory;

class Factory extends Controller
{
    
    public function initialize(){
		parent::initialize();
		self::is_login();
		Rolepower::powerguard(201202);
	}

    /**
	 * 判断账号是否登录
	 * @return boolean [description]
	 */
	private function is_login(){
		$data = UserModel::is_sessionlogin();
		if (!$data['code']) {
			$data['options'] = 'relogin';
			json($data)->send();
			exit;
		}
	}

    /**
     * 工厂列表
     */
    public function factoryList(Request $request)
    {
        $page = $request->get('page') ?? 1;
        $pageSize = $request->get('pageSize') ?? 10;
        $keyword = $request->get('keyword') ?? '';

        $result = FactoryModel::getFactoryList($page, $pageSize, $keyword);
        return json($result);
    }

    /**
     * 添加工厂
     */
    public function factoryAdd(Request $request)
    {
        $data = $request->post();
        
        $result = FactoryModel::addFactory($data);
        return json($result);
    }

    /**
     * 修改工厂
     */
    public function factoryEdit(Request $request)
    {
        $data = $request->post();
        
        if (empty($data['id'])) {
            return json(['code' => 0, 'msg' => '工厂ID不能为空']);
        }

        $id = $data['id'];
        unset($data['id']); 
        
        $result = FactoryModel::updateFactory($id, $data);
        return json($result);
    }

    /**
     * 删除工厂
     */
    public function factoryDel()
    {
        $id=input('id');
        if(!$id){
            return json(['code' => 0, 'msg' => '工厂ID不能为空']);
        }
        $factoryData=FactoryModel::get($id);
        if(!$factoryData){
            return json(['code' => 0, 'msg' => '工厂不存在']);
        }

        FactoryModel::destroy($id);
        return json(['code' => 1, 'msg' => '删除成功']);
    }

    /**
     * 工厂管理员列表
     */
    public function factoryAdminList()
    {
        $factoryId=input('factoryId');
        $result=FactoryModel::factoryAdminList($factoryId);
        return json($result);
    }

    /**
     * 给工厂添加对应的管理员
     */
    public function factoryAdminAdd()
    {
        $data=input('post.');
        $result=FactoryModel::factoryAdminAdd($data);
        return json($result);
    }
    /**
     * 删除工厂管理员
     */

    public static function factoryAdminDel()
    {
        $userId=input('id');
        $userData=UserModel::get($userId);
        
        if(!$userData){
            return json(['code'=>false,'msg' =>'管理员信息不存在']);
        }
        UserModel::where('UserId',$userId)->delete();
        UserFactory::delUserFactory($userId);
        return json(['code'=>true,'msg'=>'删除成功']);
    }
}